package com.example.beikeyigou.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.beikeyigou.login_reg.UserBean;

// 用户登录成功后，保存到本地的工具类

/**
 * Android本地保存的三种方式
 *      1. 共享参数文件保存
 *      2. file存储
 *      3. 数据库存储
 */
public class SaveUserUtils {
    public static UserBean.DataBean userData = null;
    // 将用户个人信息保存到内存中
    public static boolean saveUserToMemory(UserBean.DataBean bean) {
        userData = bean;
        return true;
    }

    // 将用户登录的个人信息保存到文件
    public static boolean saveUserToFile(Context context, UserBean.DataBean data){
        // 共享参数保存数据的步骤
        // 1.获取共享参数对象
        SharedPreferences pref = context.getSharedPreferences("user", Context.MODE_PRIVATE);
        // 2.获取编辑对象
        SharedPreferences.Editor editor = pref.edit();
        // 3.开始写入数据
        editor.putInt("id", data.getId());
        editor.putString("phone", data.getPhone());
        editor.putString("password", data.getPassword());
        editor.putString("name", data.getName());
        editor.putString("address", data.getAddress());
        editor.putString("nickname", data.getNickname());
        editor.putString("question", data.getQuestion());
        editor.putString("answer", data.getAnswer());
        // 4.提交结果
        editor.commit();
        // 数据保存到内存
        saveUserToMemory(data);
        return true;
    }

    // 获取用户信息数据
    public static UserBean.DataBean getUserFromFile(Context context) {
        // 获取数据的步骤
        // 1.获取共享参数对象
        SharedPreferences pref = context.getSharedPreferences("user", Context.MODE_PRIVATE);
        // 2.获取数据
        UserBean.DataBean bean = new UserBean.DataBean();
        bean.setId(pref.getInt("id", -1));
        bean.setPhone(pref.getString("phone", ""));
        bean.setPassword(pref.getString("password", ""));
        bean.setName(pref.getString("name", ""));
        bean.setAddress(pref.getString("address", ""));
        bean.setNickname(pref.getString("nickname", ""));
        bean.setQuestion(pref.getString("question", ""));
        bean.setAnswer(pref.getString("answer", ""));
        return bean;
    }

    /**
     * 获取用户信息：先从内存中获取，如果没有，再从文件中获取
     * @param context
     * @return
     */
    public static UserBean.DataBean getUserData(Context context) {
        if (userData != null) {
            return userData;
        }
        UserBean.DataBean user = getUserFromFile(context);
        if (user.getId() != -1) {
            userData = user;
            return userData;
        }
        return null;
    }

    public static void deleteUserData(Context context) {
        SharedPreferences pref = context.getSharedPreferences("user", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.clear();
        editor.commit();
        userData = null;
    }
}
